package jp.co.cos.ittrick.channel.controller.client;

import jp.co.cos.ittrick.channel.meta.CategoryModelMeta;
import jp.co.cos.ittrick.channel.model.CategoryModel;
import jp.co.cos.ittrick.channel.model.ChannelModel;
import jp.co.cos.ittrick.channel.service.CategoryService;
import jp.co.cos.ittrick.channel.service.ChannelService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Key;

public class InsertCategoryController extends Controller {

    CategoryService categoryService;
    ChannelService channelService;

    public InsertCategoryController() {
        categoryService = new CategoryService();
        channelService = new ChannelService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String channel = asString("channel");
        String name = asString("name");
        Integer index = this.asInteger("index");

        // 親を取得
        ChannelModel channelModel = channelService.getChannelByKey(channel);

        // Modelの設定
        CategoryModel model = new CategoryModel();
        model.setName(name);
        model.setIndex(index);
        model.getChannelModelRef().setModel(channelModel);

        // Insert
        Key key = categoryService.insert(model);

        // 再取得して返す
        model = categoryService.getCategoryByKey((int)key.getId());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().println(CategoryModelMeta.get().modelToJson(model));
        response.flushBuffer();

        return null;
    }
}
